package com.eobard.controller;

import cn.hutool.json.JSONUtil;
import com.eobard.config.obfuscate.ObfuscatorConfig;
import com.eobard.dto.ObfuscationDto;
import com.eobard.enums.RunningEnum;
import com.eobard.executor.ObfuscationExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @Author: Eobard Gu
 * @Date: 2025-08-13
 * @Description: 代码混淆控制器
 */
@RestController
@RequestMapping("/api/obfuscate")
public class ObfuscatorController {

    @Autowired
    private ObfuscationExecutor executor;
    @Autowired
    private ObfuscatorConfig obfuscatorConfig;

    @PostMapping("/startObfuscation")
    @CrossOrigin(methods = {RequestMethod.GET, RequestMethod.POST}, allowedHeaders = "*")
    public ResponseEntity obfuscate(@RequestBody ObfuscationDto obfuscationDto) {
        //基础配置信息
        obfuscatorConfig.setSourceRoot(obfuscationDto.getSourceRoot());
        obfuscatorConfig.setResourceRoot(obfuscationDto.getResourceRoot());
        RunningEnum runningEnum = obfuscationDto.isAndroidProject() ? RunningEnum.ANDROID_PROjECT : RunningEnum.JAVA_PROJECT;
        obfuscatorConfig.setRunningStatus(runningEnum);
        //核心混淆功能
        obfuscatorConfig.setRenameClassParams(obfuscationDto.getRenameClass());
        obfuscatorConfig.setRenameFieldParams(obfuscationDto.getRenameField());
        obfuscatorConfig.setRenameMethodParams(obfuscationDto.getRenameMethod());
        obfuscatorConfig.setMethodArgumentParams(obfuscationDto.getMethodArgument());
        obfuscatorConfig.setOverrideMethodParams(obfuscationDto.getInterfaceMethodArgument());
        obfuscatorConfig.setRandomRenamePackageParams(obfuscationDto.getRandomRenamePkgConfig());
        obfuscatorConfig.setClassRandomShuffleParams(obfuscationDto.getClassRandomShuffleConfig());

        //可选混淆功能
        obfuscatorConfig.setAlterMD5Params(obfuscationDto.getMd5Config());
        obfuscatorConfig.setPackageRemoveParams(obfuscationDto.getRenamePackage());
        obfuscatorConfig.setRenameResourceParams(obfuscationDto.getAndroidResConfig());
        obfuscatorConfig.setMnnConverterParams(obfuscationDto.getMnnConfig());

        //执行混淆
        executor.obfuscate(obfuscatorConfig);
        HashMap<String, Object> res = new HashMap<>();
        res.put("data", "混淆成功");
        return new ResponseEntity(JSONUtil.toJsonStr(res), HttpStatus.OK);
    }
}
